package util

import (
	"io"
	"net/http"

	"gitee.com/shoyer/logger"
	"github.com/spf13/cast"
)

// const
const (
	ContentTypeApplicationJSON = "application/json"
)

// Get Get
func Get(url string) (string, error) {
	resp, err := http.Get(url)
	if err != nil {
		logger.Error(err.Error())
		return "", err
	}

	defer resp.Body.Close()

	body, err2 := io.ReadAll(resp.Body)
	if err2 != nil {
		logger.Error(err2)
		return "", err2
	}

	return cast.ToString(body), nil
}

// Post Post
func Post(url, contentType string, data io.Reader) (string, error) {
	resp, err := http.Post(url, contentType, data)

	if err != nil {
		logger.Error(err.Error())
		return "", err
	}

	defer resp.Body.Close()

	body, err2 := io.ReadAll(resp.Body)
	if err2 != nil {
		logger.Error(err2)
		return "", err2
	}

	return cast.ToString(body), nil
}

// GetBytes GetBytes
func GetBytes(url string) ([]byte, error) {
	resp, err := http.Get(url)
	if err != nil {
		logger.Error(err.Error())
		return nil, err
	}

	defer resp.Body.Close()

	body, err2 := io.ReadAll(resp.Body)
	if err2 != nil {
		logger.Error(err2)
		return nil, err2
	}

	return body, nil
}
